package com.atguigu.gmall.payment.rest;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.atguigu.gmall.common.constant.RabbitConst;
import com.atguigu.gmall.common.util.JSONs;
import com.atguigu.gmall.mq.config.component.RabbitService;
import com.atguigu.gmall.payment.config.properties.AlipayProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * @Author:lyd
 * @Date:2023/9/6 23:25
 * @Version:1.0
 * @Description 用于处理支付宝异步通知的消息
 **/

@RestController
@RequestMapping("/api/payment")
@Slf4j
public class PayNotifyController {

    @Autowired
    RabbitService rabbitService;
    @Autowired
    AlipayProperties alipayProperties;
    @PostMapping("/notify/success")
    public String paySuccessNotify(@RequestParam Map<String, String> params) throws AlipayApiException {
        log.info("收到支付宝异步通知...内容:{}", JSONs.toJSONStr(params));


        //调用SDK验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(params,
                alipayProperties.getAlipayPublicKey(), alipayProperties.getCharset(), alipayProperties.getSignType());
        if (signVerified) {
            //验签成功，说明是支付宝发送的消息
            log.info("验签成功");

            //在这里修改订单状态；记得做所有事情之前必须验签
            rabbitService.sendMsg(RabbitConst.EXCHANGE_ORDER_EVENT,RabbitConst.RK_ORDER_PAYED,params);
            return "success";
        }else {
            log.info("验签失败");
            return "error";
        }
    }
}
